package com.zy.dpbc.webdemo

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast

/**
 * @author: shalei
 * @since: 2021/2/27 12:19 PM
 * @Desc:
 **/
class DemoHtmlView(context: Context, attrs: AttributeSet?, defStyle: Int) : WebView(context, attrs, defStyle) {

    companion object {
        const val URL = "file:///android_asset/meipian/index.html"
    }

    constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0)

    constructor(context: Context): this(context, null)

    init {
        settings.javaScriptEnabled = true
        webChromeClient = WebChromeClient()
        webViewClient = createWebClient()
        isEnabled = true
        requestFocus(View.FOCUS_DOWN)
        loadUrl(URL)
        addListener()
    }

    @SuppressLint("JavascriptInterface")
    private fun addListener() {
        addJavascriptInterface(Handler(this), "Bridge2")
    }

    private fun createWebClient(): WebViewClient {
        return WebViewClient()
    }


    fun sendData(text: String) {
        evaluateJavascript("javascript:Bridge.onSend4Java('$text')", null)
    }
}

class Handler(private val webView: DemoHtmlView) {

    @JavascriptInterface
    fun onSend4Js(text: String) {
        val activity = webView.context as Activity
        activity.runOnUiThread {
            Toast.makeText(activity, "来自js 的消息 $text", Toast.LENGTH_SHORT).show()
        }
    }

    @JavascriptInterface
    fun adb(ss: String) {
        Log.e("sdfds", "sd ")
    }
}